package com.cinema.api.handler;

import com.cinema.api.model.enums.ResultCodeEnum;
import com.cinema.api.model.exception.BizException;
import com.cinema.api.model.result.Result;
import com.cinema.api.utils.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理类
 * @author 谢泓泓
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public Result bizExceptionHandler(BizException e) {
        log.error("发生业务异常！:{}",e.getErrorMsg());
        return Result.error(e.getErrorCode(), e.getErrorMsg());
    }
    /**
     * 处理空指针异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public Result nullPointerExceptionHandler(NullPointerException e) {
        log.error("发生空指针异常！：", e);
        return Result.setResult(ResultCodeEnum.NULL_POINT);
    }
    /**
     * 权限不足
     * @param e
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public Result accessDeniedException(AccessDeniedException e) {
        if (e.getClass().equals(AccessDeniedException.class)){
            return Result.setResult(ResultCodeEnum.NO_PERMISSION);
        }
        log.error(e.getMessage());
        return Result.error();
    }
    /**
     * Http请求方法不支持
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Object handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("Http请求方法不支持:", e);
        return Result.setResult(ResultCodeEnum.SYS_REQUEST_METHOD_NOT_SUPPORTED);
    }
    /**
     * 非法请求参数
     */
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    @ResponseBody
    public Object handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("非法请求参数:", e);
        return Result.setResult(ResultCodeEnum.PARAM_ERROR);
    }
    /**
     * 处理其他异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e) {
        log.error("未知异常:",e);
        log.error(ExceptionUtil.getMessage(e));
        return Result.error();
    }

}
